from common.sqlalchemy_package import *
from flask import g
from datetime import datetime


class Log(BaseModel):
    __tablename__ = 'log'
    log_id = mapped_column(Integer, primary_key=True)  #操作id
    log_user = mapped_column(String)#操作对象
    log_content = mapped_column(Text)  # 操作内容
    log_time = mapped_column(DateTime)  # 操作时间


   # 添加操作记录
    @staticmethod
    def add_log(log_user,log_content):
        try:
            log=Log(log_user=log_user,log_content=log_content,log_time=datetime.now())
            g.db_session.add(log)
            g.db_session.commit()
            return 0
        except:
            return -1

    #获取全部操作日记
    @staticmethod
    def query_log_all(page):
        per_page = 8  # 每页返回的数据量
        start_index = (int(page) - 1) * per_page  # 计算每页数据的起始索引
        query = g.db_session.query(Log)
        # 查询满足条件的记录总数
        total_count = query.count()
        # 计算总页数
        total_pages = (total_count + per_page - 1) // per_page
        # 分页查询并逆向排序
        results = query.order_by(Log.log_id.desc()).limit(per_page).offset(start_index).all()
        return results,total_pages

    # 根据时间模糊查询操作日记
    @staticmethod
    def log_time_search(log_time):
        
        return g.db_session.query(Log).filter(Log.log_time.like('%' +log_time+ '%')).order_by(
            Log.log_id.desc()).all()

    # 删除操作日记
    @staticmethod
    def del_log(log_id):
        try:
            query = g.db_session.query(Log).filter(Log.log_id == int(log_id)).first()
            g.db_session.delete(query)
            g.db_session.commit()
            return 0
        except Exception as e:
            print(e)
            return -1

